<template>
  <div class="emrHistory-container">
    <xm-card-header title="历史就诊" btnType="primary"></xm-card-header>
    <span style="margin-right: 12px">类型</span>
    <el-radio-group v-model="radioActive" @change="radioChange">
      <el-radio-button label="全部"></el-radio-button>
      <el-radio-button label="首诊"></el-radio-button>
      <el-radio-button label="复诊"></el-radio-button>
      <!-- <el-radio-button label="旧病历"></el-radio-button> -->
    </el-radio-group>
    <el-collapse
      class="emrHistory-collapse"
      v-model="collapseActive"
      @change="handeleChange"
    >
      <el-collapse-item
        v-for="(item, index) in list"
        :key="index"
        :name="item.emrId"
      >
        <template #title>
          <div class="collapse-hubs">
            <span>{{ item.doctors }}</span>
            <template v-if="item.type !== 'oldEmr'">
              <span v-if="item.riskUserName">{{ item.riskUser }}</span>
              <!-- <span>{{ item.recordDate }}</span> -->
              <!-- <span>{{ item.content }}</span> -->
              <span>{{ item.medicalConsultationsTime }}</span>
              <!-- <span>{{ item.endDate }}</span> -->

              <el-button type="text" disabled @click.stop="printEmr(item)">
                打印病历
              </el-button>
              <el-button type="text" disabled @click.stop="printRecipel">
                打印处方
              </el-button>
              <el-button
                type="text"
                @click.stop="withdraw(item, item.isSubmit)"
              >
                {{ item.isSubmit ? '病历撤回' : '编辑病历' }}
              </el-button>

              <el-button type="text">查看</el-button>
            </template>
            <template v-else>
              <el-button
                type="text"
                :disabled="hasOldIndex(item)"
                @click.stop="toOldEmrWeb(item)"
              >
                去儿童哮喘标准化平台查看
              </el-button>
              <el-button type="text">查看</el-button>
            </template>
          </div>
        </template>
        <emr-info
          v-model="item.emrData"
          :isReview="item.treatmentType === 0"
        ></emr-info>
      </el-collapse-item>
      <template v-if="list.length === 0">
        <div style="margin-left: 10px; color: #909399; line-height: 60px">
          暂无数据
        </div>
      </template>
    </el-collapse>
    <XmPagination
      v-if="radioActive !== '旧病历'"
      style="bottom: 5px; position: relative"
      :total="total"
      @pagination="paginaChange"
    ></XmPagination>
    <emr-template ref="emrPrintRef" @success="imgToSave"></emr-template>
  </div>
</template>
<script>
  import { reactive, toRefs, ref, computed } from '@vue/reactivity'
  import emrInfo from './emrInfo.vue'
  import XmCardHeader from 'XMC/XmCardHeader'
  import { loadEmrFullHistory, loadOldEmr } from '@/api/modules/patient'
  import { nextTick, onBeforeMount } from '@vue/runtime-core'
  import { useRoute, useRouter } from 'vue-router'
  import { useStore } from 'vuex'
  import common from '@/utils/common.js'
  import { convertEmrWithOldEmr } from '@/hooks/oldEmr/useEmrContent.js'
  import { withdrawEmrWithEmrId } from '@/api/modules/emr'
  import { withdrawActionPlan } from '@/api/modules/actionPlan'
  export default {
    name: 'emrHistory',
    components: { emrInfo, XmCardHeader },
    setup() {
      const d = reactive({
        radioActive: '全部',
        list: [],
        total: null,
        search: { pageIndex: 1, pageSize: 5, type: 0 },
        collapseActive: [],
      })
      const route = useRoute()
      const store = useStore()
      const loadData = async function (params) {
        const dic = { 全部: null, 首诊: 1, 复诊: 0 }
        const res = await loadEmrFullHistory({
          ...params,
          patientId: route.query.id,
          treatmentType: dic[d.radioActive],
        })
        d.list = res.data.map((item) => {
          const {
            treatmentType,
            departmentName,
            doctorName,
            recordDate,
            type,
            outpatientNo,
            roomNo,
            bedNo,
            id,
            medicalConsultationsTime,
            endDate,
            historicalVisitId,
          } = item
          const dic = {}
          dic['doctors'] = `${
            treatmentType === 1 ? '首诊' : '复诊'
          }-${departmentName}-${doctorName}`
          dic['recordDate'] = recordDate
          dic['content'] =
            type === 0
              ? `门诊号:${outpatientNo}`
              : `住院号:${outpatientNo} 房号:${roomNo} 床号:${bedNo}`
          dic['emrId'] = id
          dic['vid'] = historicalVisitId
          dic['emrData'] = item
          dic['riskUser'] = '筛查人:' + item.riskUserName
          dic['riskUserName'] = item.riskUserName
          dic['medicalConsultationsTime'] =
            '接诊日期:' +
            (medicalConsultationsTime ? medicalConsultationsTime : '暂无数据')
          dic['endDate'] = '结束日期:' + (endDate ? endDate : '暂无数据')
          dic['isSubmit'] = item.status === 2 ? true : false
          dic['isAction'] =
            item.actionPlanDto && item.actionPlanDto.status === 2 ? true : false
          dic['treatmentType'] = treatmentType
          return dic
        })
        console.log('d.list =' + JSON.stringify(d.list))
      }

      const loadOldData = async function () {
        const { id, birthday } = store.getters.patientInfo
        const oldEmr = await loadOldEmr({ patientId: id })
        const oldEmrList = oldEmr.data.map((item, index) => {
          return convertEmrWithOldEmr(item, birthday)
        })
        d.list = oldEmrList
      }
      onBeforeMount(() => {
        loadData(d.search)
        if (route.query.emrId) d.collapseActive = [+route.query.emrId]
      })
      const paginaChange = function (params) {
        d.search.pageIndex = params.current
        d.search.pageSize = params.pageSize
        loadData(d.search)
      }

      const printRecipel = function () {
        console.log('点击答应处方')
      }

      const handeleChange = function (activeNames) {
        console.log('点击了折叠 =' + JSON.stringify(activeNames))
      }

      const radioChange = async function () {
        if (d.radioActive === '旧病历') {
          await nextTick()
          loadOldData()
        } else {
          loadData(d.search)
        }
      }

      const emrPrintRef = ref(null)
      const printEmr = function (row) {
        console.log('打印病历' + JSON.stringify(row))
        emrPrintRef.value.init(row.emrId, true, status)
      }
      const imgToSave = function () {
        console.log('病历图片生成完成')
      }
      const toOldEmrWeb = function (item) {
        common.XmAlert(
          '即将在儿童哮喘平台打开该页面，是否打开（需要互联网访问权限）',
          () => {
            // 要不要去旧病历
            const { patientDocumentId, patientId } = item.emrData
            let url = null
            if (item.isReview) {
              // eslint-disable-next-line max-len
              url = `https://c-sams.com/login?redirectUrl=https%3A%2F%2Fc-sams.com%2Femr%2Freview%3Fpid%3D${patientId}%26emrid%3D${patientDocumentId}`
            } else {
              // eslint-disable-next-line max-len
              url = `https://c-sams.com/login?redirectUrl=https%3A%2F%2Fc-sams.com%2Femr%2Ffirst%3Fpid%3D${patientId}%26emrid%3D${patientDocumentId}`
            }
            // https://c-sams.com/emr/review
            window.open(url, '_blank')
          }
        )
      }
      const hasOldIndex = computed(() => (item) => {
        const { patientDocumentId, patientId } = item.emrData
        if (patientDocumentId && patientId) {
          return false
        } else {
          return true
        }
      })
      const router = useRouter()
      async function withdraw(item, isWithDraw, isEmr) {
        if (!isWithDraw) {
          router.push({
            name: 'medicalRecord',
            query: { id: route.query.id, vid: item.vid, emrId: item.emrId },
          })
          return
        }
        await common.syncAlert('确定撤回已提交的病历？病历修改需谨慎操作？')
        common.XmLoading(true)
        withdrawEmrWithEmrId({ medicalRecordId: item.emrId })
          .then(async () => {
            common.XmLoading(false)
            common.XmMessage(0, '撤回成功！')
            // Todo 刷新页面
            loadData(d.search)
            await common.syncAlert('是否要前往编辑病历')
            router.push({
              name: 'medicalRecord',
              query: { id: route.query.id, vid: item.vid, emrId: item.emrId },
            })
          })
          .catch(() => {
            common.XmLoading(false)
          })
      }
      async function withdrawActionplan(item, isWithDraw) {
        if (!isWithDraw) {
          router.push({
            name: 'treatmentPlan',
            query: { id: route.query.id, vid: item.vid, emrId: item.emrId },
          })
        } else {
          withdrawActionPlan({ medicalRecordId: item.emrId })
            .then(async () => {
              common.XmLoading(false)
              common.XmMessage(0, '撤回成功！')
              loadData(d.search)
            })
            .catch(() => {
              common.XmLoading(false)
            })
        }
      }
      return {
        printEmr,
        printRecipel,
        handeleChange,
        paginaChange,
        radioChange,
        imgToSave,
        emrPrintRef,
        toOldEmrWeb,
        hasOldIndex,
        withdraw,
        withdrawActionplan,
        ...toRefs(d),
      }
    },
  }
</script>
<style lang="scss" scoped>
  @import '~@/styles/mixin.scss';
  .emrHistory-container {
    background-color: white;
    margin-top: 32px;
    padding: 15px;
    @include card-shadow;

    .emrHistory-collapse.el-collapse {
      margin-top: 12px;
      .collapse-hubs {
        width: 100%;
        overflow: hidden;
        line-height: 40px;
        span {
          color: #97a8be;
          margin-left: 12px;
        }
        .el-button {
          float: right;
          margin-right: 11px;
        }
      }
    }
  }
</style>
